package com.cuitrip.business.user;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.cuitrip.apiservice.ServiceBusiness;
import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.home.IndexActivity;
import com.cuitrip.business.home.trip.TripServiceListFragment;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.setting.SubmitSuccessActivity;
import com.cuitrip.business.setting.model.SubmitSuccessModel;
import com.cuitrip.business.tripservice.model.FormType;
import com.cuitrip.business.tripservice.model.SelectMenu;
import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.business.tripservice.proxy.ServiceFormProxy;
import com.cuitrip.business.tripservice.ui.SelectMenuFragment;
import com.cuitrip.business.user.identity.IdentityMode;
import com.cuitrip.business.user.identity.ImageBitmap;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.business.user.modules.MInput1Activity;
import com.cuitrip.component.item.ItemLayout;
import com.cuitrip.service.R;
import com.cuitrip.util.JumpSuccessUtil;
import com.cuitrip.util.ResourceUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragment;
import com.lab.logtrack.AppLog;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.photopicker.DefaultCallback;
import com.lab.photopicker.EasyImage;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.GetImageHelper;
import com.lab.utils.ImageHelper;
import com.lab.utils.MessageUtils;
import com.lab.utils.ToastUtil;
import com.lab.utils.Utils;
import com.lab.utils.imageupload.imp.QiniuService;
import com.lab.utils.imageupload.model.QiniuTokenObject;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by sheena on 16/5/16.
 */
public class VerifyIDFragment extends CustomUiFragment implements IProxyCallback{
    @Bind(R.id.v1)
    View mStep1;

    @Bind(R.id.v2)
    View mStep2;

    @Bind(R.id.v3)
    View mStep3;

    @Bind(R.id.il_id_type)
    ItemLayout mIdTypeLayout;

    @Bind(R.id.iv_id_pic)
    ImageView mIdPic;

    private String[] idTypes;
    private ApiProxy mApiProxy=new ApiProxy(this);
    private String type;
    private String picUrl;


    private static final int REQUEST_CODE_ID_SUCCESS=0X01;
    private static final String TYPE_IDCARD="1";
    private static final String TYPE_PASSPORT="2";
    private ServiceInfo mServiceInfo;

    public static VerifyIDFragment newInstance(ServiceInfo serviceInfo, CtUserInfo mUserInfo) {
        VerifyIDFragment verifyIDFragment = new VerifyIDFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ServiceInfo.KEY,serviceInfo);
        verifyIDFragment.setArguments(bundle);
        return verifyIDFragment;
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarMiddleAreaName = getString(R.string.trip_operation_profile_title_1);
        config.mRightStyle= CustomUiConfig.AreaStyle.TEXT_STYLE;
        config.mTopbarRightAreaName=getString(R.string.operation_skip);
        return config;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState, R.layout.fragment_verify_id);
        if (getArguments()!=null){
            mServiceInfo = (ServiceInfo) getArguments().getSerializable(ServiceInfo.KEY);
        }
        return view;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this,getView());
        mStep1.setBackgroundColor(ResourceUtil.getThemeColor());
        mStep2.setBackgroundColor(ResourceUtil.getThemeColor());
        mStep3.setBackgroundColor(ResourceUtil.getThemeColor());
    }

    @Override
    public void initData() {
        idTypes = new String[]{getString(R.string.user_attribute_id_document),getString(R.string.user_attribute_id_document_type_value_passport)};
    }

    @OnClick(R.id.il_id_type)
    public void chooseIdType(){
        SelectMenuFragment selectMenuFragment = new SelectMenuFragment();
        final List<SelectMenu> selectMenuList = new ArrayList<>();
        for (int i = 0; i < idTypes.length; i++) {
            SelectMenu selectMenu = new SelectMenu();
            selectMenu.key = String.valueOf(i);
            selectMenu.value = idTypes[i];
            selectMenuList.add(selectMenu);
        }
        selectMenuFragment.setTitle(getString(R.string.user_attribute_id_document_type));
        selectMenuFragment.setSelectMenuList(selectMenuList);
        showDialogFragment(selectMenuFragment);
        selectMenuFragment.setResultListener(new SelectMenuFragment.OnDataSelectBackListener() {

            @Override
            public void onSelect(SelectMenu selectMenu) {
                int i = Integer.parseInt(selectMenu.key);
                if (i==0){
                    type=TYPE_IDCARD;
                }else{
                    type=TYPE_PASSPORT;
                }
                mIdTypeLayout.setmRightText(selectMenuList.get(i).value);
            }
        });
    }

    @OnClick(R.id.fl_id_pic)
    public void uploadIdPic(){
        EasyImage.openChooser(this, "", true);
    }

    public void setImage(ImageView view, ImageBitmap imageBitmap) {
        if (TextUtils.isEmpty(imageBitmap.getUrl())) {
            view.setImageBitmap(imageBitmap.getBitmap());
        } else {
            ImageHelper.displayCtImage(imageBitmap.getUrl(), view, null);
        }
    }

    @OnClick(R.id.tv_btn_submit)
    public void submit(){
        if (TextUtils.isEmpty(picUrl)){
            MessageUtils.showToast(getString(R.string.trip_operation_profile_id_desc_2));
            return;
        }

        if (TextUtils.isEmpty(type)){
            Utils.shakeView(mIdTypeLayout);
        }
        UserBusiness.verifyId(mApiProxy,picUrl,type);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (REQUEST_CODE_ID_SUCCESS==requestCode){
            if (resultCode== Activity.RESULT_OK){
                mServiceInfo.setOnlineState(ServiceInfo.ONLINE_STATE);
                ServiceBusiness.commitServiceInfo(mApiProxy, mServiceInfo);
            }
        }

        EasyImage.handleActivityResult(requestCode, resultCode, data, getHostActivity(), new DefaultCallback() {
            @Override
            public void onImagePickerError(Exception e, EasyImage.ImageSource source) {
                //Some error handling
            }

            @Override
            public void onImagePicked(File imageFile, EasyImage.ImageSource source) {
                //Handle the image
                Bitmap bp = GetImageHelper.getResizedBitmap(getHostActivity(), Uri.fromFile(imageFile));
                if (bp == null) {
                } else {
                    ImageBitmap imageBitmap = new ImageBitmap();
                    imageBitmap.setBitmap(bp);
                    uploadBitmap(imageBitmap, imageFile);
                    setImage(mIdPic,imageBitmap);
                }
            }

            @Override
            public void onCanceled(EasyImage.ImageSource source) {
                //Cancel handling, you might wanna remove taken photo if it was canceled
                if (source == EasyImage.ImageSource.CAMERA) {
                    File photoFile = EasyImage.lastlyTakenButCanceledPhoto(AppCoreRuntime.context);
                    if (photoFile != null) photoFile.delete();
                }
            }
        });
    }

    public void uploadBitmap(final ImageBitmap imageBitmap, final File file) {
        showLoading();
        QiniuService.INSTANCE.requestTokenObject(new QiniuService.RequestQiniuTokenCallback() {
            @Override
            public void onSuccess(QiniuTokenObject qiniuTokenObject) {
                CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
                QiniuService.INSTANCE.asyncPutImage(QiniuService.getObjectName(userInfo.getUid()), file.getAbsolutePath(), new QiniuService.UploadCallback() {


                    @Override
                    public void onSuccess(String url) {
                        picUrl = url;
                        imageBitmap.setUrl(url);
                        hideLoading();
                    }

                    @Override
                    public void onFailure(String errorMessage) {
                        ToastUtil.toast(getString(R.string.feedback_upload_fail));
                        hideLoading();
                    }

                    @Override
                    public void onProgress(int progress) {
                        AppLog.d("progress" + progress);
                        hideLoading();
                    }
                });
            }

            @Override
            public void onFailed(String errorMessage) {
                ToastUtil.toast(errorMessage);
                hideLoading();
            }
        });
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        if (!isAdded()){
            return false;
        }
        CtApiResponse response= (CtApiResponse) result.getData();
        if (response.isResponseNormal()){
            if (ApiManager.UPLOAD_CREDIT_INFO.equals(response.getApiName())) {
                mServiceInfo.setOnlineState(ServiceInfo.ONLINE_STATE);
                ServiceBusiness.commitServiceInfo(mApiProxy, mServiceInfo);
                LoginInstance.getInstance().getUserInfo().setIdCheckStatus(CtUserInfo.ID_CHECK_ING);

            }if (ApiManager.SERVICE_COMMIT.equals(response.getApiName())){
                if (response.result instanceof ServiceInfo) {
                    ServiceInfo serviceInfo = (ServiceInfo) response.result;
                    mServiceInfo.setSid(serviceInfo.getSid());
                    LocalBroadcastManager.getInstance(AppCoreRuntime.context).sendBroadcast(
                            new Intent(TripServiceListFragment.TRIP_SERVICE_STATUS_CHANGED));
                    if (mServiceInfo.getOnlineState()==ServiceInfo.ONLINE_STATE) {
                        JumpSuccessUtil.navigate2CreateTripSucPage(VerifyIDFragment.this, REQUEST_CODE_ID_SUCCESS);
                    }else {
                        IndexActivity.gotoTab(getActivity(), IndexActivity.SERVICE_TAB_INDEX);
                        getActivity().finish();
                    }
                }
            }
        }

        return false;
    }

    @Override
    public void onTopbarRightPress() {
        if (mServiceInfo!=null) {
            if (mServiceInfo.isUnSync() || mServiceInfo.isCheckFailed() || mServiceInfo.isDraft() || mServiceInfo.isChecking()) {
                if (ServiceFormProxy.getInstance().isFormComplete(mServiceInfo, FormType.TITLE)) {
                    showLoading();
                    mServiceInfo.setOnlineState(ServiceInfo.DRAFT_STATE);
                    ServiceBusiness.commitServiceInfo(mApiProxy, mServiceInfo);
                }
            }
        }

    }
}
